package com.woniu113.junk.user.util;

import cn.hutool.json.JSONUtil;
import com.woniu113.junk.user.dto.SFRZDTO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SFRZUtil {

    public SFRZDTO sfrz(String realName,String idCard) throws Exception {
        System.out.println(realName);
        System.out.println(idCard);
        System.out.println("******************");
        String host = "https://kzidcardv1.market.alicloudapi.com";
        String path = "/api-mall/api/id_card/check";
        String method = "POST";
        String appcode = "04808f91721f40e39c98337b88ed446e";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("name", realName);
        bodys.put("idcard", idCard);

        //获取response的body
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        // 只读取一次响应体并保存到变量中
        String sfrz = EntityUtils.toString(response.getEntity());
        System.out.println("Response: " + sfrz);
        // 将 JSON 字符串解析为 Map
        Map<String, Object> responseMap = JSONUtil.toBean(sfrz, Map.class);
        // 提取 data 部分
        Map<String, Object> dataMap = (Map<String, Object>) responseMap.get("data");
        // 将 data 部分映射到 SFRZDTO 对象
        SFRZDTO sfrzdto = JSONUtil.toBean(JSONUtil.toJsonStr(dataMap), SFRZDTO.class);
        System.out.println("sfrzdto: " + sfrzdto);
        return sfrzdto;
    }

}
